<template>
  <div class="container">
    <div class="content-wrapper">
      <div class="search-section">
        <el-form label-width="60px" :model="queryForm" class="search-form">
          <div class="basic-search-row">
            <el-form-item style="margin-bottom: 0px" label="用户名">
              <el-input
                v-model.trim="queryForm.username"
                placeholder="请输入用户名"
                clearable
                prefix-icon="Search"
                @keyup.enter="getUserList"
                style="width: 200px"
              ></el-input>
            </el-form-item>

            <div class="search-actions">
              <el-button type="primary" icon="Search" @click="getUserList">搜索</el-button>
              <el-button icon="RefreshRight" @click="resetQuery">重置</el-button>
              <el-button :icon="isAdvancedSearchVisible ? 'ArrowUp' : 'ArrowDown'" @click="toggleAdvancedSearch">
                {{ isAdvancedSearchVisible ? '收起' : '展开' }}
              </el-button>
            </div>
          </div>

          <div v-if="isAdvancedSearchVisible" class="advanced-search-row">
            <el-form-item label="姓名" style="margin-bottom: 0px">
              <el-input
                v-model.trim="queryForm.name"
                placeholder="请输入姓名"
                clearable
                prefix-icon="User"
                @keyup.enter="getUserList"
                style="width: 200px"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮箱" style="margin-bottom: 0px">
              <el-input
                v-model.trim="queryForm.email"
                placeholder="请输入邮箱"
                clearable
                prefix-icon="Message"
                @keyup.enter="getUserList"
                style="width: 200px"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>

        <div class="operation-container">
          <el-button type="primary" icon="Plus" @click="addUser">新增用户</el-button>
          <el-tooltip content="刷新数据" placement="top" effect="light">
            <el-button icon="RefreshRight" circle @click="getUserList"></el-button>
          </el-tooltip>
        </div>
      </div>

      <div class="table-section">
        <el-table v-loading="loading" :data="userList" border stripe highlight-current-row class="user-table">
          <el-table-column type="index" width="60" align="center" label="序号" />
          <el-table-column prop="username" label="用户名" min-width="120" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              <span>{{ row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" align="center" min-width="120" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" align="center" min-width="180" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.email }}
            </template>
          </el-table-column>
          <el-table-column label="角色" align="center" min-width="150">
            <template #default="{ row }">
              <el-space wrap :size="4">
                <el-tag
                  v-for="userRole in row.userRoles"
                  :key="userRole.role.roleId"
                  class="role-tag"
                  :type="getRoleTagType(userRole.role.roleId)"
                  effect="light"
                >
                  <el-icon><UserFilled /></el-icon>
                  {{ userRole.role.roleName }}
                </el-tag>
              </el-space>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="remark" label="备注" align="center" min-width="150" />
          <el-table-column prop="status" label="状态" align="center" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                @change="handleStatusChange(row)"
                inline-prompt
                active-icon="Check"
                inactive-icon="Close"
                active-text="启用"
                inactive-text="停用"
                :loading="row.statusLoading"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              <el-tooltip :content="row.createTime" placement="top" effect="light">
                <span class="time-cell">
                  {{ row.createTime }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="80" align="center">
            <template #default="{ row }">
              <el-tooltip content="编辑用户" placement="top" effect="light">
                <el-button type="primary" link icon="Edit" @click="handleEditUser(row)"></el-button>
              </el-tooltip>
              <el-popconfirm
                title="确定要删除该用户吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="Warning"
                icon-color="#ff4949"
                :title-style="{ color: '#1e293b', fontSize: '14px', fontWeight: 500 }"
                @confirm="handleDeleteUser(row)"
              >
                <template #reference>
                  <el-button type="danger" link icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="queryForm.page"
          v-model:page-size="queryForm.size"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="onSizeChange"
          @current-change="onPageChange"
          background
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <edit-user ref="editUserRef" @refresh="getUserList" />
  </div>
</template>

<script setup>
  import { useUserApi } from '@/api/user-api.js';
  import { DialogType, RStatus } from '@/common/comstants.js';
  import editUser from './components/EditUser.vue';

  let userList = reactive([]);
  let total = ref(0);
  let loading = ref(false);

  // 查询form
  const queryForm = reactive({
    username: '',
    name: '',
    email: '',
    status: '',
    page: 1,
    size: 10,
  });
  const editUserRef = ref();

  const isAdvancedSearchVisible = ref(false);

  const toggleAdvancedSearch = () => {
    isAdvancedSearchVisible.value = !isAdvancedSearchVisible.value;
  };

  const resetQuery = () => {
    queryForm.username = '';
    queryForm.name = '';
    queryForm.email = '';
    queryForm.status = '';
    isAdvancedSearchVisible.value = false;
    getUserList();
  };

  onMounted(() => {
    getUserList();
  });

  /** 分页大小变更 */
  const onSizeChange = (size) => {
    queryForm.size = size;
    getUserList();
  };

  /** 分页页码变更  */
  const onPageChange = (page) => {
    queryForm.page = page;
    getUserList();
  };

  /** 获取用户列表 */
  const getUserList = async () => {
    loading.value = true;

    try {
      const res = await useUserApi().getUserList(queryForm);
      if (res.status === RStatus.SUCCESS) {
        userList = res.data.users;
        total.value = res.data.total;
      }
    } finally {
      loading.value = false;
    }
  };

  /** 新增用户 */
  const addUser = () => {
    editUserRef.value.openDialog();
  };

  /** 更新用户信息 */
  const handleEditUser = (user) => {
    editUserRef.value.openDialog(DialogType.EDIT, user);
  };

  /** 更新用户状态 */
  const handleStatusChange = async (row) => {
    loading.value = true;
    try {
      const res = await useUserApi().updateUser(row);
      if (res.status === RStatus.SUCCESS) {
        await getUserList();
        ElMessage.success(res.message);
      }
    } finally {
      loading.value = false;
    }
  };

  /** 删除用户 */
  const handleDeleteUser = async (row) => {
    loading.value = true;
    try {
      const res = await useUserApi().deleteUser(row.username);
      if (res.status === RStatus.SUCCESS) {
        await getUserList();
        ElMessage.success(res.message);
      } else {
        ElMessage.error(res.message);
      }
    } finally {
      loading.value = false;
    }
  };

  // 获取角色标签类型
  const getRoleTagType = (roleId) => {
    const types = ['', 'success', 'warning', 'info', 'danger'];
    return types[roleId % types.length];
  };
</script>

<style lang="scss" scoped>
  .container {
    background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);

    .content-wrapper {
      background: white;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

      .search-section {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .search-form {
          display: flex;
          flex-direction: column;
          background-color: rgba(249, 250, 251, 0.6);
          backdrop-filter: blur(8px) saturate(150%);
          border: 1px solid rgba(229, 231, 235, 0.3);
          padding: 15px;
          border-radius: 12px;
          transition: all 0.3s ease;

          .basic-search-row {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 0;
          }

          .advanced-search-row {
            margin-top: 15px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
          }

          .search-actions {
            display: flex;
            align-items: center;
            gap: 10px;
          }
        }

        .operation-container {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          gap: 10px;
          flex-wrap: wrap;
        }
      }

      .table-section {
        margin-bottom: 20px;

        .user-table {
          width: 100%;
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: flex-end;
      margin-top: 15px;
    }
  }

  .user-cell {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 6px 8px;
    border-radius: 8px;
    transition: background-color 0.3s ease;

    .el-avatar {
      flex-shrink: 0;
      border: 2px solid #e5e7eb;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition:
        transform 0.3s ease,
        box-shadow 0.3s ease;
    }

    span {
      font-weight: 500;
      color: #374151;
      transition: color 0.3s ease;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    &:hover {
      background-color: rgba(59, 130, 246, 0.05);

      .el-avatar {
        transform: scale(1.05);
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.15);
      }

      span {
        color: #3b82f6;
      }
    }
  }

  .user-table {
    .el-table__header {
      background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);

      th {
        background: transparent;
        color: #1f2937;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        border-bottom: 2px solid #e5e7eb;
      }
    }

    .el-table__body {
      tr {
        transition: background-color 0.3s ease;

        &:hover {
          background-color: rgba(59, 130, 246, 0.02);
        }

        &.current-row {
          background-color: rgba(59, 130, 246, 0.1) !important;
        }
      }

      td {
        padding: 12px 8px;
        color: #374151;
      }
    }
  }
</style>
@/api/user-api